package com.rjkj.medicalwaste.adapter

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.rjkj.medicalwaste.bean.BleDeviceBean
import com.rjkj.medicalwaste.databinding.ItemBluetoothListBinding

class BluetoothDeviceAdapter(private val itemClick: ItemClick<BleDeviceBean>): RecyclerView.Adapter<BluetoothDeviceAdapter.BluetoothDeviceViewHolder>() {
    private val list = mutableListOf<BleDeviceBean>()
    val set = mutableSetOf<BleDeviceBean>()
    inner class BluetoothDeviceViewHolder(private val itemBluetoothListBinding: ItemBluetoothListBinding) : RecyclerView.ViewHolder(itemBluetoothListBinding.root) {
        fun bind(item:BleDeviceBean){
            itemBluetoothListBinding.device = item
            itemBluetoothListBinding.executePendingBindings()
        }
    }
    fun cleanData(){
        list.clear()
        set.clear()
        notifyDataSetChanged()
    }
    fun addData(bean: BleDeviceBean){
        if(set.add(bean)){
            list.add(bean)
            notifyItemInserted(list.size-1)
        }

    }
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BluetoothDeviceViewHolder {
        return BluetoothDeviceViewHolder(
            ItemBluetoothListBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    override fun getItemCount(): Int {
        return list.size
    }

    override fun onBindViewHolder(holder: BluetoothDeviceViewHolder, position: Int) {
        holder.apply {
            bind(list[position])
            itemView.setOnClickListener {
                itemClick.onClicked(it,list[position])
            }
        }
    }
}